<template>
  <div class="app-container">
    <h1>截取视频视频案例</h1>
    <div class="display-block">
      <video class="small-video" id="video" autoplay controls ref="video"></video>
      <canvas class="small-canvas" ref="canvas"></canvas>
    </div>
    <el-button @click="takeSnap" size="small">截屏</el-button>
  </div>
</template>
<script>
import { defineComponent, onMounted, reactive, toRefs,ref } from "vue";

export default defineComponent({
  setup() {
    const state = reactive({
      stream: null,
      videoTracks: []
    });
    let video=ref(null)
    let canvas=ref(null)
    const constraints = (window.constraints = {
      audio: false,
      video: true,
    });
    onMounted(()=>{
      handleOpen()
    })
    const handleOpen =async () => {
      try {
        const stream = await navigator.mediaDevices.getUserMedia(constraints);
        handleSuccess(stream)
      } catch (e) {
        console.log(e)
      }
    };
    const handleSuccess = (stream) => {
      state.stream = stream;
      let tmpV = document.getElementById("video");
      state.videoTracks = stream.getVideoTracks();
      console.log(state.videoTracks);
      console.log("使用的设备是:" + state.videoTracks[0].label);
      window.stream = stream;
      tmpV.srcObject=state.stream
    };
    const takeSnap=async ()=>{
      console.log(canvas.value)
      console.log(video.value)
      canvas.value.width=500
      canvas.value.height=500
      canvas.value.getContext('2d').drawImage(video.value,0,0,canvas.value.width,canvas.value.height)
    }
    return {
      ...toRefs(state),
      handleOpen,
      video,
      takeSnap,
      canvas
    };
  },
});
</script>
<style scoped>
.app-container {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}
.display-block{
  width: 100%;
  height: auto;
  display: flex;
  flex-direction: row;
  justify-content: space-around;
}
.small-video{
  width: 300px;
  height: 300px;
  border: 1px solid black;
}
.small-canvas{
  width: 300px;
  height: 300px;
  border: 1px solid black;
}
</style>
